package com.example.treasureadmin.controller;

import com.alibaba.fastjson.JSONObject;
import com.example.treasureadmin.entity.MsgEntity;
import com.example.treasureadmin.service.UserService;
import com.example.treasureadmin.shiroentity.auth.AuthUser;
import com.example.treasureadmin.model.UserModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/treasure-admin")
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping("/user/all")
    public MsgEntity getAllUsers(@AuthUser String username){
        List<UserModel> all = userService.getAll();
        for (UserModel userModel : all) {
            userModel.setPassword("");
        }
        System.out.println(username);
        return new MsgEntity("200","SUCCESS",all);
    }

    @GetMapping("/user/{id}")
    public MsgEntity getUserId(@PathVariable("id") String id)
    {
        UserModel all = userService.userFind(id);
        if(all == null)
        {
            return new MsgEntity("200","SUCCESS","用户不存在");
        }
        return new MsgEntity("200","SUCCESS",all);
    }

    @PutMapping("/user/password")
    public MsgEntity updatePassword(@RequestBody JSONObject requestBody)
    {
        String email = requestBody.getString("email");
        String password = requestBody.getString("password");
        String code = userService.changePassword(email, password);
        if(code.equals("200"))
        {
            return new MsgEntity("200","SUCCESS","修改成功");
        }
        return new MsgEntity("200","SUCCESS","用户不存在");
    }

    @DeleteMapping("/user/{id}")
    public MsgEntity deleteUserId(@PathVariable("id") String id)
    {
        String code = userService.logOut(id);
        if(code.equals("200"))
        {
            return new MsgEntity("200","SUCCESS","注销成功");
        }
        return new MsgEntity("200","SUCCESS","用户不存在");
    }

    @PutMapping("/user/{id}")
    public MsgEntity unBlock(@PathVariable("id") String id)
    {
        String code = userService.unBlock(id);
        if(code.equals("200"))
        {
            return new MsgEntity("200","SUCCESS","解封成功");
        }
        return new MsgEntity("200","SUCCESS","用户不存在");
    }
}

